package com.shxt.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shxt.model.User;
import com.shxt.service.UserService;
import com.shxt.util.PageBean;

@Controller
@RequestMapping("/sys")
public class UserController {
	@Autowired
	private UserService userService;
	/**
	 * 将分页的员工数据传到user.jsp
	 * @param user
	 * @param map
	 * @param pages
	 * @return
	 */
	@RequestMapping("/userList")
	public String userList (User user, Map<String, Object> map,@RequestParam(required=false,defaultValue="1") int pages) {
		map = PageBean.serverMap(map , user , pages);
        List<User> userList = userService.list(map);
        Integer count = userService.count(map);
        map = PageBean.map(map , user.getClass() , userList , count , pages);
        map.put("url" , "sys/userList");
        return "/user/user";
	}
	/**
	 * 查看单个员工的详细信息
	 * @param user_id
	 * @param model
	 * @return
	 */
	@RequestMapping("/getUser/{user_id}")
	public String getUser (@PathVariable Integer user_id, Model model) {
		model.addAttribute("getUser", userService.load(user_id));
		return "/user/getUser";
	}
	/**
	 * 删除员工
	 * @param user_id
	 * @return
	 */
	@RequestMapping("/delUser")
	@ResponseBody
	public int delUser (Integer user_id) {
		return userService.delete(user_id);
	}
	/**
	 * 跳转到添加员工界面
	 * @return
	 */
	@GetMapping("/addUser")
	public String addUser () {
		return "/user/addUser";
	}
	/**
	 * 添加员工
	 * @param user
	 * @param model
	 * @param response
	 * @return
	 */
	@PostMapping("/addUser")
	public String addUser (User user,Model model,HttpServletResponse response) {
		int n = userService.add(user);
		PrintWriter out;
		try {
			out = response.getWriter();
			if (n == 1) {
				out.print("<script>alert('添加成功！');</script>");
			}else {
				out.print("<script>alert('添加失败！');</script>");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "/user/user";
	}
}
